package com.tasks.table;

import org.apache.log4j.Logger;
import com.tasks.server.*;

public class User extends Table {
	
	static Logger logger = Logger.getLogger(User.class);
	
	private static final Column userName 	= new Column("USERNAME", 	Column.TEXT);
	private static final Column password 	= new Column("PASSWORD", 	Column.TEXT);
	private static final Column firstName 	= new Column("FIRSTNAME",	Column.TEXT);
	private static final Column lastName 	= new Column("LASTNAME", 	Column.TEXT);
	private static final Column email 		= new Column("EMAIL", 		Column.TEXT);
	
	private static final Column columns[] 	= new Column[]
	{
		userName, 
		password, 
		firstName, 
		lastName, 
		email
	};
		
	public User(Server s, Executor exe)
	{
		super(s, exe, columns);
	}

	public User(String user, String pass, String first, String last, String mail) 
	{
		addColumn(userName, user);
		addColumn(password, hashPassword(pass));
		addColumn(firstName, first);
		addColumn(lastName, last);
		addColumn(email, mail);
	}
	
	private String hashPassword(String pw)
	{
		try
		{
			MD5 md = MD5.getInstance();
			return md.hashData(pw.getBytes());
		}
		catch(Exception e)
		{
			new ServerException(User.class, "hashPassword", "Error hashing the password");
		}
		return null;
	}
	
	// overridden from the super class to allow password hashing
	public void set(String columnName, Object o)
	{
		if(columnName.toUpperCase().compareTo("PASSWORD") == 0)
		{
			super.set(columnName, hashPassword((String)o));
		}
		else 
		{
			super.set(columnName, o);
		}
	}
	
	public static User fetchById(Server server, Integer id)
	{
		Executor executor = new Executor(server);
		User user = null;
		
		String sql = "SELECT * " 
				   + "FROM USER "
				   + "WHERE USERID = " + id + ";";
		
		if(executor.execute(sql))
		{
			user = new User(server, executor);
		}
		executor.close();
		executor = null;
		
		return user;
	}
}
